package site.teamo.biu.net.client.core.http_https_proxy.client;

import com.alibaba.fastjson2.JSON;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import site.teamo.biu.net.client.configuration.ClientConfiguration;
import site.teamo.biu.net.client.controller.model.server_management.Server;
import site.teamo.biu.net.client.service.impl.ServerManagementServiceImpl;
import site.teamo.biu.net.common.coder.MessageDecoder;
import site.teamo.biu.net.common.coder.MessageEncoder;
import site.teamo.biu.net.common.constant.ChannelAttributeKey;
import site.teamo.biu.net.common.constant.Protocol;
import site.teamo.biu.net.common.handler.ExceptionHandler;
import site.teamo.biu.net.common.handler.SimpleTransferHandler;
import site.teamo.biu.net.common.http_https_proxy.ChannelGroups;
import site.teamo.biu.net.common.message.connect_to_destination_address.ConnectToDestinationAddressRequest;
import site.teamo.biu.net.common.message.connect_to_destination_address.ConnectToDestinationAddressResponse;
import site.teamo.biu.net.common.util.HostPort;
import site.teamo.biu.net.common.util.HttpUtils;
import site.teamo.biu.net.common.web.mapper.SystemConfigMapper;
import site.teamo.biu.tool.spring.util.SpringApplicationContextHolder;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author haocongshun
 * @date 2023/06/08 14:32:38
 */
@Slf4j
public class ProxyTransferClient {

    private final EventLoopGroup group;

    private HostPort hostPort;

    private final String clientId;

    private String token;

    private final Bootstrap bootstrap;

    @Getter
    private final ChannelGroups channelGroups;

    private final Timer timer;

    //入流量统计
    private final AtomicLong in;

    //出流量统计
    private final AtomicLong out;

    public ProxyTransferClient(AtomicLong in, AtomicLong out) {
        this.in = in;
        this.out = out;
        this.group = new NioEventLoopGroup();
        Server server = getServer();
        this.hostPort = server.getProxyServer();
        this.token = server.getToken();
        this.clientId = getClientId();
        this.bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new Initializer());
        this.channelGroups = new ChannelGroups();
        this.timer = new Timer(true);
        this.timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Server tempServer = getServer();
                if (!tempServer.getProxyServer().equals(hostPort) || !tempServer.getToken().equals(token)) {
                    hostPort = tempServer.getProxyServer();
                    token = tempServer.getToken();
                }
            }
        }, 0, 30000L);
    }

    public void http(HostPort hostPort, Channel channelFromBrowser, HttpRequest request) {
        Channel channelToProxyServer = establishConnection(hostPort, channelFromBrowser);
        channelToProxyServer.attr(ChannelAttributeKey.HTTP_REQUEST).setIfAbsent(request);
        channelToProxyServer.attr(ChannelAttributeKey.IS_HTTPS).setIfAbsent(false);
    }

    public void https(HostPort hostPort, Channel channelFromBrowser) {
        Channel channelToProxyServer = establishConnection(hostPort, channelFromBrowser);
        channelToProxyServer.attr(ChannelAttributeKey.IS_HTTPS).setIfAbsent(true);
    }

    public void close() {
        this.channelGroups.close();
        this.group.shutdownGracefully();
        this.timer.cancel();
    }

    private Channel establishConnection(HostPort hostPort, Channel channelFromBrowser) {
        try {
            Channel channelToProxyServer = this.bootstrap.connect(this.hostPort.host(), this.hostPort.port()).sync().channel();
            channelFromBrowser.attr(ChannelAttributeKey.TARGET_CHANNEL).setIfAbsent(channelToProxyServer);
            channelToProxyServer.attr(ChannelAttributeKey.TARGET_CHANNEL).setIfAbsent(channelFromBrowser);
            channelToProxyServer.writeAndFlush(
                            new ConnectToDestinationAddressRequest(
                                    clientId,
                                    token,
                                    hostPort.protocol(),
                                    hostPort.host(),
                                    hostPort.port()))
                    .addListener(future -> {
                        if (future.isSuccess()) {
                            channelToProxyServer.pipeline().remove("message-encoder");
                            channelGroups.put(hostPort, channelFromBrowser);
                            log.debug("客户端已经向代理服务器发送使用[{}]协议连接{}:{}的请求", hostPort.protocol(), hostPort.host(), hostPort.port());
                        } else {
                            channelToProxyServer.close();
                            channelFromBrowser.close();
                        }
                    });
            return channelToProxyServer;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private Server getServer() {
        SystemConfigMapper systemConfigMapper = SpringApplicationContextHolder.getBean(SystemConfigMapper.class);
        String id = ClientConfiguration.HTTP_HTTPS_PROXY_SERVICE_USED_SERVER_ID.getContent(systemConfigMapper);
        ServerManagementServiceImpl service = SpringApplicationContextHolder.getBean(ServerManagementServiceImpl.class);
        return service.queryServer(id);
    }

    private String getClientId() {
        SystemConfigMapper systemConfigMapper = SpringApplicationContextHolder.getBean(SystemConfigMapper.class);
        return ClientConfiguration.CLIENT_ID.getContent(systemConfigMapper);
    }

    private class Initializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast("message-decoder", new MessageDecoder("代理客户端"))
                    .addLast("message-encoder", new MessageEncoder("代理客户端"))
                    .addLast("proxy", new Handler())
                    .addLast("idle", new IdleStateHandler(0, 0, 90, TimeUnit.SECONDS))
                    .addLast("exception", new ExceptionHandler());
        }
    }

    private class Handler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof ConnectToDestinationAddressResponse connectToDestinationAddressResponse) {
                log.debug("代理服务器已与{}:{}建立连接", connectToDestinationAddressResponse.host(), connectToDestinationAddressResponse.port());
                Channel channelToProxyServer = ctx.channel();
                channelToProxyServer.pipeline().remove(this);
                if (connectToDestinationAddressResponse.ok()) {
                    Channel channelFromBrowser = channelToProxyServer.attr(ChannelAttributeKey.TARGET_CHANNEL).get();
                    //移除与代理服务器通信的channel的消息解码器
                    channelToProxyServer.pipeline().remove("message-decoder");
                    channelToProxyServer.pipeline().addBefore("exception", "simple-transfer", new SimpleTransferHandler("代理客户端向代理服务器转发请求", out));
                    channelFromBrowser.pipeline().addBefore("exception", "simple-transfer", new SimpleTransferHandler("代理客户端向浏览器转发响应", in));
                    Boolean isHttps = channelToProxyServer.attr(ChannelAttributeKey.IS_HTTPS).get();
                    if (isHttps) {
                        https(channelFromBrowser);
                        log.info("连接到{}:{}的[HTTPS]通道已建立", connectToDestinationAddressResponse.host(), connectToDestinationAddressResponse.port());
                        channelFromBrowser.attr(ChannelAttributeKey.DESTINATION_INFO).setIfAbsent(HostPort.of(
                                Protocol.HTTPS,
                                connectToDestinationAddressResponse.host(),
                                connectToDestinationAddressResponse.port()));
                        channelFromBrowser.config().setAutoRead(true);
                    } else {
                        http(channelFromBrowser, channelToProxyServer);
                        log.info("连接到{}:{}的[HTTP]通道已建立", connectToDestinationAddressResponse.host(), connectToDestinationAddressResponse.port());
                        channelFromBrowser.attr(ChannelAttributeKey.DESTINATION_INFO).setIfAbsent(HostPort.of(
                                Protocol.HTTP,
                                connectToDestinationAddressResponse.host(),
                                connectToDestinationAddressResponse.port()));
                        channelFromBrowser.config().setAutoRead(true);
                    }
                }

            } else {
                ctx.fireChannelRead(msg);
            }
        }

        private void http(Channel channelFromBrowser, Channel channelToProxyServer) {
            channelFromBrowser.pipeline().remove("http-decoder");
            channelFromBrowser.pipeline().remove("http-encoder");
            HttpRequest request = channelToProxyServer.attr(ChannelAttributeKey.HTTP_REQUEST).get();
            if (request == null) {
                return;
            }
            //通道建立以后，需要把当前这一条http请求数据转发到服务端去
            //要将http的数据转换成首先将接受的请求转换成原始字节数据
            Object msg = HttpUtils.convertHttpRequestToOriginalMsg(request);
            channelToProxyServer.writeAndFlush(msg);
        }

        private void https(Channel channelFromBrowser) {
            channelFromBrowser.pipeline().remove("http-decoder");
            //向浏览器答复ok后，就可以将http的编解码器移除了
            channelFromBrowser.writeAndFlush(HttpUtils.okResponse())
                    .addListener(future -> {
                        if (future.isSuccess()) {
                            channelFromBrowser.pipeline().remove("http-encoder");
//                            log.info("向浏览器答复ok后，来自浏览器的channel:{}", NettyUtil.printPipeline(channelFromBrowser));
                        } else {
                            channelFromBrowser.close();
                        }
                    });
        }
    }

}
